package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.representer.Represent;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        //获取所有的日期存放到list集合中
        List<LocalDate> localDateList = new ArrayList<>();

        List<Double> turnoverList = new ArrayList<>();

        while(!begin.equals(end.plusDays(1)))
        {
            begin = begin.plusDays(1);
            localDateList.add(begin);

            //统计日期营业额
            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN); //当天00：00
            LocalDateTime endTime = LocalDateTime.of(begin, LocalTime.MAX);
            Double turnover =  orderMapper.getTurnoverStatistics(beginTime,endTime, Orders.COMPLETED);
            turnover = turnover==null?0:turnover;  //等于空为0
            turnoverList.add(turnover);
        }

        //遍历集合获取每天的开始和截止时间(可以只遍历一次) 封装成LocalDateTime 状态未已完成 总额 查询sql

        return TurnoverReportVO.builder().dateList(StringUtils.join(localDateList,","))
                .turnoverList(StringUtils.join(turnoverList,",")).build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        //计算日期
        List<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);

        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList  = new ArrayList<>();

        //统计截止日期用户总数量 一条sql查开始日期 递增查新增用户
        //统计第一天
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN); //当天00：00
        LocalDateTime endTime = LocalDateTime.of(begin, LocalTime.MAX);
        Map<String,LocalDateTime> map = new HashMap<>();
        map.put("end",endTime);
        //beginTime的总用户
        Integer totalUser =  userMapper.getUser(map);
        totalUserList.add(totalUser);

        //循环查每天新增的用户
        map.put("begin",beginTime);
        Integer newUer =  userMapper.getUser(map);
        newUserList.add(newUer);

        while (!begin.equals(end))
        {
            begin  = begin.plusDays(1);
            localDateList.add(begin);

            beginTime = LocalDateTime.of(begin, LocalTime.MIN); //当天00：00
            endTime = LocalDateTime.of(begin, LocalTime.MAX);

            Map<String,LocalDateTime> map2 = new HashMap<>();
            map2.put("begin",beginTime);
            map2.put("end",endTime);

            //循环查每天新增的用户
             newUer =  userMapper.getUser(map2);
            totalUser =totalUser + newUer;

            totalUserList.add(totalUser);
            newUserList.add(newUer);
        }


        return UserReportVO
                .builder()
                .dateList(StringUtils.join(localDateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN); //当天00：00
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10List = orderMapper.getSalesTop(beginTime,endTime);

        List<String> nameList = salesTop10List.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());

        List<Integer> numberList = salesTop10List.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO
                .builder().nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出数据报表
     * @param response
     */
    @Override
    public void exportBussinessDate(HttpServletResponse response) {
        //读取近30天的营业数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        BusinessDataVO businessData = workspaceService.getBusinessData
                                     (LocalDateTime.of(begin, LocalTime.MIN),
                                      LocalDateTime.of(end, LocalTime.MAX));

        //通过poi写进excel文件中
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //获取对象
            XSSFWorkbook excel = new XSSFWorkbook(is);

            //获取sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //获取第二行的的二个单元格并填充数据
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);
            //获取第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细
            for (int i = 0; i < 30; i++) {
                LocalDate localDate =  begin.plusDays(i);
                BusinessDataVO date = workspaceService.getBusinessData(LocalDateTime.of(localDate, LocalTime.MIN), LocalDateTime.of(localDate, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(localDate.toString());
                row.getCell(2).setCellValue(date.getTurnover());
                row.getCell(3).setCellValue((date.getValidOrderCount()));
                row.getCell(4).setCellValue(date.getOrderCompletionRate());
                row.getCell(5).setCellValue(date.getUnitPrice());
                row.getCell(6).setCellValue(date.getNewUsers());
            }

            //通过输出流将excel下载到浏览器
            ServletOutputStream os = response.getOutputStream();
            excel.write(os);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
